<template>
  <div class="report-form">
    <div class="page__header">
      <button class="page__header-btn-back" @click="$router.go(-1)"></button>
      能源充电日报报表
      <button class="page__header-btn-link" @click="$router.go(-1)">专题</button>
    </div>
    <div class="title-bg">
      {{showDate}}能源充电日报报表
      <button type="button" class="title-bg__btn" @click="tipDialog.show = true"></button>
      <div class="title-tip">（能源充电日报数据均来源于能源系统，与能源系统出具的日报数据保持一致）</div>
    </div>
    <div class="pd-aside bg-white" style="padding: 8px 10px;">
      <div class="selects">
        <!--       时间选择框（开始时间）-->
        <div class="selects__item select-date" @click="chooseDate('startDate')">
          {{datePickerProvince.showData}}
        </div>
        <div style="margin-top: 4px;"> - </div>
        <!--        时间选择器（结束时间）-->
        <div class="selects__item select-date" @click="chooseDate('endDate')">
          {{endDatePickerProvince.showData}}
        </div>
        <!--        地域选择框-->
        <div class="selects__item select-address" @click="provinceInfo.show = true">
          {{provinceInfo.showArea}}
        </div>
      </div>
    </div>
    <div class="page__main bg-white">
      <div class="page__scroller">
        <div class="pd-aside" style="height: 100%;">
          <FixedTable :data="table" @tableDataSort="getTableData()" @passSort="passSort" @passTag="passTag" @passChinese="passChinese"></FixedTable>
        </div>
        <WaterMark :length="3"></WaterMark>
      </div>
    </div>
    <!--    开始时间选择器-->
    <van-popup
      v-model="datePickerProvince.show"
      position="bottom"
      :style="{ height: '40%' }"
    >
      <van-datetime-picker
        v-model="datePickerProvince.currentDate"
        ref="startDate"
        type="date"
        :min-date="datePickerProvince.minDate"
        :max-date="datePickerProvince.maxDate"
        @cancel="handleCanleDate('startDate')"
        @confirm="handleConfirmDateProvince('startDate')"
      ></van-datetime-picker>
    </van-popup>
    <!--    结束时间选择器-->
    <van-popup
      v-model="endDatePickerProvince.show"
      position="bottom"
      :style="{ height: '40%' }"
    >
      <van-datetime-picker
        v-model="endDatePickerProvince.currentDate"
        ref="endDate"
        type="date"
        :min-date="datePickerProvince.currentDate"
        :max-date="endDatePickerProvince.maxDate"
        @cancel="handleCanleDate('endDate')"
        @confirm="handleConfirmDateProvince('endDate')"
      ></van-datetime-picker>
    </van-popup>
    <van-popup
      v-model="provinceInfo.show"
      position="bottom"
      :style="{ height: '40%' }"
    >
      <van-picker
        show-toolbar
        :columns="provinceInfo.columns"
        :defaultIndex='provinceInfo.defaultIndex'
        @cancel="provinceInfo.show = false"
        @confirm="confirmFnArea"
      />
    </van-popup>
    <!--分页-->
    <van-pagination
      v-model="page"
      :page-count="total"
      :items-per-page="pageRows"
      @change="nextText"
      mode="simple"
    />
    <div class="tip-dialog" v-show="tipDialog.show">
      <div class="tip-dialog__main">
        <div class="tip-dialog__header">
          指标说明
          <button type="button" class="tip-dialog__close" @click="tipDialog.show = false"></button>
        </div>
        <div class="tip-dialog__body">
          <div class="tip-dialog__list">
            <div class="tip-dialog__item" v-for="(item, index) in tipDialog.list" :key="index">
              <div class="tip-dialog__item-title">{{item.title}}</div>
              <div class="tip-dialog__item-intro" v-show="item.intro != undefined">{{item.intro}}</div>
              <div class="tip-dialog__item-detail" v-show="item.detail != undefined">{{item.detail}}</div>
            </div>
          </div>
          <div class="footer-tip">了解更多信息，请登录PC端运营数据展示系统</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  import FixedTable from '@/components/FixedTable'
  import WaterMark from '@/components/WaterMark'

  export default {
    components: {
      FixedTable,
      WaterMark
    },
    data() {
      return {
        pageParams: {
          selectDate: this.$route.query.selectDate,
          selectArea: this.$route.query.selectArea,
        },
        passedSort: 'none',
        passedTag: '',
        passedChinese:true,
        showDate: '',
        page: 1,
        total: 1,
        pageRows: 96,
        sortable: true,
        userInfo: this.$store.state.userInfo,
        // areaId: this.$store.state.userInfo.home_city,
        areaId: '100000',
        datePickerProvince: {
          showData: '--/--/--',
          selectDate: '',
          show: false,
          currentDate: new Date(),
          minDate: new Date(),
          maxDate: new Date(),
        },
        endDatePickerProvince: {
          showData: '--/--/--',
          selectDate: '',
          show: false,
          currentDate: new Date(),
          minDate: new Date(),
          maxDate: new Date(),
        },
        provinceInfo: {
          show: false,
          defaultIndex: 0,
          showArea: '',
          selectId: this.$route.query.selectArea,
          columns: []
        },
        table: {
          fixed: true,
          fixedHead: true,
          fixedLeft: true,
          loading: false,
          reset: false,
          tableHead: [
            {title: '序号', width: 50, tag: 'SEQ_NO', fixed: true, initSort: 'asc',},
            {title: '省分', width: 70, tag: 'PROVINCE', sortable: true, fixed: true, chinese: false,},
            {
              title: '统计日期',
              width: 100,
              sortable: true,
              tag: 'STAT_DATE',
              sort: 'none',
              canFormat: false,
              chinese: true,
              fixed: false,
            },
            {
              title: '端口数(个)',
              width: 130,
              sortable: true,
              tag: 'PORTS_NUM',
              sort: 'none',
              canFormat: true,
              chinese: true
            },
            {
              title: '在线端口数(个)',
              width: 130,
              sortable: true,
              tag: 'ZAIXIAN_PORTS_NUM',
              sort: 'none',
              canFormat: true,
              chinese: true,
            },
            {
              title: '端口在线率(%)',
              width: 130,
              sortable: false,
              tag: 'ZAIXIAN_PORTS_RATIO',
              sort: 'none',
              canFormat: false,
              chinese: true,
            },
            {
              title: '累计注册客户数(户)',
              width: 130,
              sortable: true,
              tag: 'LJ_REGISTER_NUM',
              sort: 'none',
              canFormat: true,
              chinese: true,
            },
            {
              title: '累计使用客户数(户)',
              width: 130,
              sortable: true,
              tag: 'LJ_USE_NUM',
              sort: 'none',
              canFormat: true,
              chinese: true,
            },
            {
              title: '当月注册客户数(户)',
              width: 130,
              sortable: true,
              tag: 'DY_REGISTER_CUSTOMER_NUM',
              sort: 'none',
              canFormat: true,
              chinese: true,
            },
            {
              title: '当月使用客户数(户)',
              width: 130,
              sortable: true,
              tag: 'DY_USE_NUM',
              sort: 'none',
              canFormat: true,
              chinese: true,
            },
            {
              title: '当日活跃用户数(户)',
              width: 130,
              sortable: true,
              tag: 'DR_ACTIVE_NUM',
              sort: 'none',
              canFormat: true,
              chinese: true,
            },
            {
              title: '当日充电次数(次)',
              width: 130,
              sortable: true,
              tag: 'DR_CHARGE_NUM',
              sort: 'none',
              canFormat: true,
              chinese: true,
            },
            {
              title: '平均每次充电收费(元)',
              width: 130,
              sortable: true,
              tag: 'AVG_NUM_CHARGE_COST',
              sort: 'none',
              canFormat: true,
              chinese: true,
            },
            {
              title: '平均每小时充电收费(元)',
              width: 130,
              sortable: true,
              tag: 'AVG_HOUR_CHARGE_COST',
              sort: 'none',
              canFormat: true,
              chinese: true,
            },
            {
              title: '当日收入(元)',
              width: 130,
              sortable: true,
              tag: 'DR_INCOME',
              sort: 'none',
              canFormat: true,
              chinese: true,
            },
            {
              title: '用户平均充电时长(小时)',
              width: 130,
              sortable: true,
              tag: 'AVG_HOUR_CHARGE',
              sort: 'none',
              canFormat: true,
              chinese: true,
            },
            {
              title: '端口日均利用率(%)',
              width: 130,
              sortable: false,
              tag: 'RJ_PORTS_USE',
              sort: 'none',
              canFormat: false,
              chinese: true,
            },
          ],
          tableData: []
        },
        //指标口径说明
        tipDialog: {
          show: false,
          list: [
            {
              title: '端口数',
              detail: '统计期内已投入运营的设备端口统计总数量（包含在线和离线两部分）',
            },
            {
              title: '在线端口数',
              detail: '统计期内已投入运营的且设备状态为在线的设备端口统计总数量'
            },
            {
              title: '端口在线率',
              intro: '端口在线率=统计期内在线端口数/端口数'
            },
            {
              title: '累计注册客户数',
              detail: '统计期内平台内所有的客户数累加'
            },
            {
              title: '累计使用客户数',
              detail: '统计期内平台内所有的发生有效充电的（有效充电是单次充电时间大于5min）客户数累加'
            },
            {
              title: '当月注册客户数',
              detail: '统计期内平台内所有的客户数累加'
            },
            {
              title: '当月使用客户数',
              detail: '统计期内平台内所有的发生有效充电的（有效充电是单次充电时间大于5min）客户数累加'
            },
            {
              title: '当日活跃用户数',
              detail: '统计期内平台内所有的发生有效充电的（有效充电是单次充电时间大于5min）客户数累加'
            },
            {
              title: '当日充电次数',
              detail: '统计期内所有客户发生的充电总次数累计'
            },
            {
              title: '平均每次充电收费',
              intro: '平均每次充电收费=统计期内充电总收入/充电总次数'
            },
            {
              title: '平均每小时充电收费',
              intro: '平均每小时充电收费=统计期内充电总收入/充电总时长'
            },
            {
              title: '当日收入',
              detail: '统计期内充电总收入累加'
            },
            {
              title: '用户平均充电时长',
              intro: '用户平均充电时长=统计期内用户总充电时长/用户有效充电次数'
            },
            {
              title: '端口日均利用率',
              intro: '端口日均利用率=统计期内所有端口有效充电总次数/端口数（有效充电是单次充电时间大于5min）客户数累加'
            },
          ]
        }
      }
    },
    methods: {
      passSort(sort) {
        this.passedSort = sort
      },
      passTag(tag) {
        this.passedTag = tag
      },
      passChinese(chinese){
        this.passedChinese=chinese
      },
      chooseDate(state) {
        if (state === 'startDate') {
          this.datePickerProvince.show = true
        } else {
          this.endDatePickerProvince.show = true
        }
      },
      handleCanleDate(state) {
        if (state === 'startDate') {
          this.datePickerProvince.show = false
        } else {
          this.endDatePickerProvince.show = false
        }
      },
      handleConfirmDateProvince(state) {
        let currentData = state === 'startDate' ? 'datePickerProvince' : 'endDatePickerProvince'
        this[currentData].show = false

        let currentRef = this.$refs[state]
        let value = currentRef.value
        let date = new Date(value)
        let year = date.getFullYear()
        let month = date.getMonth() + 1
        let day = date.getDate()
        let month1 = month < 10 ? '0' + month : month
        let day1 = day < 10 ? '0' + day : day
        this[currentData].showData = year + '/' + month + '/' + day
        this[currentData].selectDate = year + '' + month1 + '' + day1
        // TODO 是否需要增加字段区别
        this.showDate = year + '年' + month + '月' + day + '日'
        // TODO 获取数据方法需修改
        if(this.datePickerProvince.selectDate > this.endDatePickerProvince.selectDate) {
          this.endDatePickerProvince.selectDate = this.datePickerProvince.selectDate
          this.endDatePickerProvince.showData = this.datePickerProvince.showData
        }
        this.getTableData()
      },
      //获得省分
      getProvinceInfo() {
        let params = {
          // areaId: this.$store.state.userInfo.home_city
          areaId: this.areaId
        }

        this.$http
          .post("api/yearCheckIndex/getKpiAreaInfo", params)
          .then(data => {
            //获取省会
            if (data.rows.length > 1) {
              this.provinceInfo.columns = []
              data.rows.forEach(item => {
                this.provinceInfo.columns.push({
                  text: item.area,
                  id: item.areaId
                })
              })
              this.provinceInfo.columns.unshift({text: "全国", id: "100000"})
              this.provinceInfo.columns.forEach((item, index) => {
                if (item.id == this.pageParams.selectArea) {
                  this.provinceInfo.showArea = item.text
                  this.provinceInfo.defaultIndex = index
                }
              })
            }
          });
      },
      //确认省分
      confirmFnArea(item, index) {
        if (this.provinceInfo.selectId != item.id) {
          this.provinceInfo.selectId = item.id
          this.provinceInfo.showArea = item.text
          this.passedSort = 'none'
          this.passedTag = ''
          this.passedChinese = true
          this.showDate = ''
          this.page =  1
          this.getTableData()
        }
        this.provinceInfo.show = false
      },
      //获得时间域
      getMaxMinMonth() {
        function dateSplit(param) {
          let paramStr = param + ''
          let dateStr = paramStr.replace(/(.{2})/g, '$1,')
          let dateArr = dateStr.substr(0, dateStr.length - 1).split(',')
          return dateArr
        }

        return new Promise((resolve, reject) => {
          this.$http.post('/api/yearCheckIndex/maxMonth', {type: '8'}).then(data => {
            let max = data.maps[0].MAX_MONTH
            let min = data.maps[0].MIN_MONTH

            let maxYear = dateSplit(max)[0] + dateSplit(max)[1]
            let maxMonth = dateSplit(max)[2]
            let maxDay = dateSplit(max)[3]
            let minYear = dateSplit(min)[0] + dateSplit(min)[1]
            let minMonth = dateSplit(min)[2]
            let minDay = dateSplit(min)[3]
            let actualMaxMonth = parseInt(maxMonth) - 1
            let actualMinMonth = parseInt(minMonth) - 1

            let currentDate = new Date(maxYear, actualMaxMonth, maxDay)
            let minDate = new Date(minYear, actualMinMonth, minDay)
            let maxDate = new Date(maxYear, actualMaxMonth, maxDay)

            let paramsDate = this.pageParams.selectDate
            let paramsYear = dateSplit(paramsDate)[0] + dateSplit(paramsDate)[1]
            let paramsMonth = dateSplit(paramsDate)[2]
            let paramsDay = dateSplit(paramsDate)[3]
            let paramsActualMonth = parseInt(paramsMonth) - 1
            let paramsShowMonth = paramsMonth[0] == '0' ? paramsMonth[1] : paramsMonth
            let paramsShowDay = paramsDay[0] == '0' ? paramsDay[1] : paramsDay
            let showData = paramsYear + '/' + paramsShowMonth + '/' + paramsShowDay + '/'
            let paramsCurrent = new Date(paramsYear, paramsActualMonth, paramsDay)

            this.datePickerProvince.currentDate = paramsCurrent
            this.datePickerProvince.minDate = minDate
            this.datePickerProvince.maxDate = maxDate
            this.datePickerProvince.showData = showData
            this.datePickerProvince.selectDate = paramsDate

            this.endDatePickerProvince.currentDate = paramsCurrent
            this.endDatePickerProvince.minDate = minDate
            this.endDatePickerProvince.maxDate = maxDate
            this.endDatePickerProvince.showData = showData
            this.endDatePickerProvince.selectDate = paramsDate

            this.showDate = paramsYear + '年' + paramsShowMonth + '月' + paramsShowDay + '日'
            resolve("ok")
          })
        })
      },
      //渲染表格数据
      getTableData() {
        let params = {}
        this.table.tableData = []
        this.table.loading = true
        this.table.reset = false
        params = {
          areaId: this.provinceInfo.selectId,
          stateDate: this.datePickerProvince.selectDate,
          endDate: this.endDatePickerProvince.selectDate,
          page: this.page,
          pageRows: this.pageRows,
          type: '1',
          sort: this.passedSort,
          tag: this.passedTag,
          chinese:this.passedChinese
        }
        this.$http
          .post('api/electric/chargingDay', params)
          .then(res => {
            this.table.tableData = res.rows;
            this.total = Math.ceil(res.total / 96);
            this.table.tableData.forEach(item => {
              Object.assign(item, {sort: true})
            })
            this.table.loading = false
            //this.table.reset = true
          });
      },
      nextText() {
        //重新刷新页面数据
        this.getTableData();
      },
      //记录日志
      recordLogs() {
        let params = {
          userId: this.userInfo.user_id,
          verify_code: this.userInfo.verify_code,
          priv_id: '10102122',
        }
        this.$http.post('api/new/insertLogs', params).then(res => {
        })
      },
    },
    watch: {
      passedSort(newVal) {
        if(newVal === 'none') {
          this.getTableData()
        }
      } ,
    },
    mounted() {
      this.recordLogs()
      this.getProvinceInfo()
      this.getMaxMinMonth().then(res => {
        if (res == 'ok') {
          this.getTableData()
        }
      })
    },
    beforeRouteLeave (to, from, next) {
      if (to.name == 'ReportFormCharge') {
        let formCharge = {
          selectDate: this.endDatePickerProvince.selectDate,
          selectArea: this.provinceInfo.selectId,
        }
        sessionStorage.setItem('formCharge', JSON.stringify(formCharge))
      } else {
        sessionStorage.removeItem('formCharge')
      }
      next()
    }
  }
</script>

<style lang="scss" scoped>
  .selects {
    margin-bottom: 0;

    &__item--date {
      flex: 1;
      width: 34%;
    }
  }

  .report-form {
    .title-bg {
      line-height: 1.4;
      padding-top: 18px;
      box-sizing: border-box;
      font-size: 18px;
    }

    .title-tip {
      padding: 2px 10px 0;
      font-size: 12px;
    }

    .water-mark {
      z-index: 1;
    }
  }
  .select-date {
    -webkit-box-flex: 2;
    flex: 2;
  }
  .select-address {
    -webkit-box-flex: 1;
    flex: 1;
  }
  /deep/ .van-pagination__item{
    color:#ff716b;
  }
  /deep/ .van-pagination__item--disabled {
    color: #646566;
  }
  /deep/ .van-pagination__item:active{
    color:#ff716b;
    background:none;
  }
</style>
